package com.glowdayz.glowmee;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.glowdayz.common.ImageDownloader;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.BrandCMD;

public class BrandSearchFm extends Fragment implements OnScrollListener, OnItemClickListener {
	
	String searchText = "";

	View listBrandView = null;
	ListView listBrand = null;
	
	ArrayList<BrandCMD> list = null;
	DataAdapter adapter = null;
	// Footer 레이아웃
	LinearLayout llFooter = null;
	
	/********** 페이지 구현 **********/
	private int page = 1;						// 현재 페이지
	private final static int pageSize = 20;		// 한 페이지에 보일 수
	private int totalCount = 0;
	
	boolean isData = false;
	
	LinearLayout requestLayout = null;
	
	String url = null;
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		listBrandView = inflater.inflate(R.layout.fm_product_brand, container, false);
		searchText = getArguments().getString("PARAM_brandTitle");
		
		requestLayout = (LinearLayout) listBrandView.findViewById(R.id.requestLayout);
		
        listBrand = (ListView) listBrandView.findViewById(R.id.listBrand);
        list = new ArrayList<BrandCMD>();
		
		LayoutInflater li = (LayoutInflater) listBrandView.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		llFooter = (LinearLayout) li.inflate(R.layout.list_footer, null);
		llFooter.setVisibility(View.GONE);
		listBrand.addFooterView(llFooter);
		
		listBrand.setOnScrollListener(this);
        
        list = new ArrayList<BrandCMD>();
		adapter = new DataAdapter(listBrandView.getContext(), list);
		listBrand.setAdapter(adapter);
		listBrand.setOnItemClickListener(this);
		
		url = getResources().getString(R.string.server_url) + "/glowmee/listBrandXml.do?" +
				"page=" + page + "&count=" + pageSize + "&searchText=" + searchText;
		
		(new BrandWorker()).execute();
		
        return listBrandView;
    }
	
	public class DataAdapter extends ArrayAdapter<BrandCMD> {
		
		private LayoutInflater inflater = null;

		// 생성자. 파라미터에 전달되는 List의 제너릭스 선언에 주의한다.
		public DataAdapter(Context context, List<BrandCMD> objects) {
			super(context, 0, objects);
			inflater = (LayoutInflater) listBrandView.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		// ArrayList에 할당된 각 항목을 하나씩 추출하여 list_item.xml에 표현시키는 메서드
		// 이 메서드는 ListView에 의해서 호출된다.
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			/** 모든 컴포넌트의 최상위 클래스 */
			View view = null;

			// 데이터를 저장할 View 선언. view 객체는 "list_item.xml"파일을 의미한다.
			if (convertView == null) {
				view = inflater.inflate(R.layout.list_brand_item, null);
			} else {
				view = convertView;
			}

			// 하나의 데이터 항목을 추출한다.
			final BrandCMD item = getItem(position);

			// 추출한 데이터가 존재한다면 "list_item.xml"안의 컨트롤들을 추출하여 처리한다.
			if (item != null) {
				LinearLayout brandInitialLayout = (LinearLayout) view.findViewById(R.id.brandInitialLayout);
				brandInitialLayout.setVisibility(View.GONE);
				TextView brandPromotion = (TextView) view.findViewById(R.id.brandPromotion);
				brandPromotion.setVisibility(View.GONE);
				
				ImageView productImg = (ImageView) view.findViewById(R.id.brandImg);
				TextView brandTitle = (TextView) view.findViewById(R.id.brandTitle);
				brandTitle.setText(item.getBrandTitle());
				
				if (item.getCreate_date().equals("null")) {
					productImg.setImageResource(R.drawable.empty_product);
				} else {
					ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + item.getCreate_date().trim(), productImg);
				}
			}
			return view;
		}
	}
	
	public class BrandWorker extends AsyncTask<Object, BrandCMD, Object> {
		@Override
		protected void onPreExecute() {
			llFooter.setVisibility(View.VISIBLE);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idBrand = 0;
				String brandTitle = null;
				String thumbnail = null;
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							totalCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idBrand")) {
							parser.next();
							idBrand = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("brandTitle")) {
							parser.next();
							brandTitle = parser.getText();
						} else if (tag.equals("thumbnail")) {
							parser.next();
							thumbnail = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("item")) {
							BrandCMD item = new BrandCMD(idBrand, brandTitle, thumbnail);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(BrandCMD... param) {
			isData = true;
			adapter.add(param[0]);
		}

		@Override
		protected void onPostExecute(Object param) {
			llFooter.setVisibility(View.GONE);
			if (!isData) {
				requestLayout.setVisibility(View.VISIBLE);
				Index.isListProduct = true;
			}
		}
		
		@Override
		protected void onCancelled() {
			llFooter.setVisibility(View.GONE);
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new BrandWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					getActivity().finish();
				}
			});
			alert.create();
			alert.show();
		}
	}

	// 화면에 리스트의 마지막 아이템이 보여지는 체크
	boolean lastItemVisibleFlag = false;
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		lastItemVisibleFlag = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && lastItemVisibleFlag) {
			int pageCount = ((totalCount -1) / pageSize) + 1;
			if (pageCount > 0 && page < pageCount) {
				page++;
				url = getResources().getString(R.string.server_url) + "/glowmee/listBrandXml.do?" +
						"page=" + page + "&count=" + pageSize + "&searchText=" + searchText;
				(new BrandWorker()).execute();
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		BrandCMD select = adapter.getItem(arg2);
		
		Intent intent = new Intent(listBrandView.getContext(), ListBrandProduct.class);
		intent.putExtra("PARAM_id", select.getIdBrand());
		intent.putExtra("PARAM_title", select.getBrandTitle());
		startActivity(intent);
	}
}